from typing import Any, Dict, Optional
from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel

from ...core.database import DatabaseUtils
from ...core.config import settings
from ..dependencies import analysis_service_dependency
from ...services.analysis_service import AnalysisService


router = APIRouter()


class NaturalLanguageQuery(BaseModel):
    query: str
    database_type: Optional[str] = None
    connection_config: Optional[Dict[str, Any]] = None


class SQLQuery(BaseModel):
    sql: str
    params: Optional[Dict[str, Any]] = None
    limit: Optional[int] = 1000


@router.post("/natural-language")
async def natural_language_query(
    req: NaturalLanguageQuery,
    analysis_service: AnalysisService = Depends(analysis_service_dependency),
):
    try:
        result = await analysis_service.analyze_query(
            query=req.query,
            database_type=req.database_type or settings.target_db_type,
            connection_config=req.connection_config,
        )
        return {
            "success": True,
            "message": "查询执行成功",
            "data": result.get("data"),
            "row_count": result.get("row_count"),
            "sql_generated": result.get("sql"),
            "columns": result.get("columns"),
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"查询执行失败: {e}")


@router.post("/sql")
async def sql_query(req: SQLQuery):
    try:
        res = DatabaseUtils.execute_target_query(req.sql, req.params or {})
        if hasattr(res, "fetchall"):
            rows = [dict(r._mapping) for r in res.fetchall()]
            if req.limit and len(rows) > req.limit:
                rows = rows[: req.limit]
            return {"success": True, "message": "OK", "data": rows, "row_count": len(rows)}
        return {
            "success": True,
            "message": "OK",
            "data": {"affected_rows": getattr(res, "rowcount", 0)},
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"SQL执行失败: {e}")


@router.get("/tables")
async def list_tables():
    tables = DatabaseUtils.get_target_tables()
    return {"success": True, "data": {"tables": tables, "count": len(tables)}}


@router.get("/tables/{table}/schema")
async def table_schema(table: str):
    schema = DatabaseUtils.get_target_table_schema(table)
    return {"success": True, "data": schema}


